<?php

namespace app\common\model\general;

use think\Model;


class LihuaSlide extends Model
{

    // 表名
    protected $table = 'lihua_slide';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    //protected $createTime = false;
    //protected $updateTime = false;
    //protected $deleteTime = false;

    // 追加属性
    protected $append = [];
    
    // 插入记录后更新排序
    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    // 获取城市轮播图
    public static function getCitySlideList($city_id = 0)
    {
        $now = date('Y-m-d');
        $map = [
            'city_id' => $city_id,
            'start_date' => ['<=', $now],
            'end_date' => ['>=', $now]
        ];
        $list = [];
        $res  = self::where($map)->order('weigh', 'desc')->select();
        foreach ($res as $k => $v) {
            $list[] = [
                'title' => $v['title'],
                'pic'   => config('site_url') . $v['pic'],
                'url'   => !$v['url'] && $v['content'] ? '' : $v['url'],
            ];
        }
        return $list;
    }

    // 关联城市模型
    public function lihuacity()
    {
        return $this->belongsTo('app\common\model\general\LihuaCity', 'city_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
